<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%-- 引入公用JSP --%>
<%@ include file="/WEB-INF/include/taglib.jsp"%>
<%-- 加入自定义UI标签库 --%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- EasyUI -->
<link rel="stylesheet" type="text/css" href="${pageScope.staticPath}/jQueryEasyUI/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="${pageScope.staticPath}/jQueryEasyUI/themes/icon.css">
<link rel="stylesheet" type="text/css" href="${pageScope.staticPath}/jQueryEasyUI/themes/ExpandIcon.css">
<script type="text/javascript" src="${pageScope.staticPath}/jQueryEasyUI/jquery.min.js"></script>
<script type="text/javascript" src="${pageScope.staticPath}/jQueryEasyUI/jquery.easyui.min.js"></script>
<script type="text/javascript" src="${pageScope.staticPath}/jQueryEasyUI/locale/easyui-lang-zh_CN.js"></script>

<script type="text/javascript" src="${staticPath}/JQueryPlugin/jQuery-File-Upload/jquery.ui.widget.js"></script>
<script type="text/javascript" src="${staticPath}/JQueryPlugin/jQuery-File-Upload/jquery.iframe-transport.js"></script>
<script type="text/javascript" src="${staticPath}/JQueryPlugin/jQuery-File-Upload/jquery.fileupload.js"></script>
<script type="text/javascript" src="${staticPath}/CryptoJS/rollups/md5.js"></script>
<script type="text/javascript" src="${staticPath}/CryptoJS/components/lib-typedarrays-min.js"></script>
<title>文件上传</title>
</head>
<body>
	<h3>文件上传Demo,使用插件：jQuery-File-Upload、CryptoJS</h3>

	<div>
		<h4>使用不同的方式，显示上传进度</h4>
		<input id="fileupload001" type="file" name="files[]" > <br/>
		<div id="dropzone001" style="background: #cccccc;width: 500px;height: 70px;text-align: center;">拖放文件到此处上传</div>
		progressbar: <div id="progressbar001-1" class="easyui-progressbar" style="width:500px;"></div><br/>
		progressallbar: <div id="progressbar001-2" class="easyui-progressbar" style="width:500px;"></div><br/>
		从服务器端获取进度:<div id="progressbar001-3" class="easyui-progressbar" style="width:500px;"></div><br/>
		
		<script>
		$(document).ready(function () {
			$("#fileupload001").fileupload({
				url : "${pageScope.mvcPath}/fileupload/upload",
				type : "POST",
				dataType : "json",
				dropZone: $('#dropzone001'),
				submit : function (e, data) {
					$.messager.alert('提示','submit');
				},
				send : function (e, data) {
					$.messager.alert('提示','send');
				},
				done : function (e, data) {
					$.messager.alert('提示','done');
				},
				fail : function (e, data) {
					$.messager.alert('提示','fail');
				},
				progress : function (e, data) {
				    var progress = parseInt(data.loaded / data.total * 100, 10);
				    $('#progressbar001-1').progressbar('setValue', progress);
				},
				progressall : function (e, data) {
				    var progress = parseInt(data.loaded / data.total * 100, 10);
				    $('#progressbar001-2').progressbar('setValue', progress);
				},
				start : function (e) {
					setTimeout(getFileuploadProgress, 100);
					$.messager.alert('提示','start');
				},
				stop : function (e) {
					$.messager.alert('提示','stop');
				},
				change : function (e, data) {
					$.messager.alert('提示','change');
				}
			});
		});
		
		function getFileuploadProgress(){
			var fun = arguments.callee;
			$.post("${pageScope.mvcPath}/fileupload/fileuploadProgress", function (data) {
				if(data.hasOwnProperty("object")){
					$('#progressbar001-3').progressbar('setValue', data.object.percentage);
					setTimeout(fun, 500);
				}
			}, "json");
		}
		</script>
	</div>
	<hr/>
	
	<div>
		<h4>每个文件一个上传进度条，可以取消上传</h4>
		<input id="fileupload002" type="file" multiple="multiple" name="files[]" > <br/>
		<div id="progressDiv" >
			上传文件总进度：<div id="progressbar002" class="easyui-progressbar" style="width:500px;"></div><br/>
		</div>
		
		<script type="text/javascript">
		$(document).ready(function () {
			$("#fileupload002").fileupload({
				url : "${pageScope.mvcPath}/fileupload/upload",
				type : "POST",
				dataType : "json",
				dropZone: $('#dropzone001'),
		        add: function (e, data) {
		        	for(var i =0 ; i < data.files.length ; i++ ) {
		        		var file = data.files[i];
		        		$('<span/>').css("margin-right","20px").text('文件：' + file.name).appendTo($("#progressDiv"));
		        		$('<button/>').css("margin-right","20px").text('上传').appendTo($("#progressDiv")).click(function () {
		        			data.submit();
		        		});
		        		$('<button/>').css("margin-right","20px").text('取消').appendTo($("#progressDiv")).click(function () {
		        			data.abort();
		        		});
		        		var progressbarID = ("ID" + Math.random()).replace(".","");
		        		$('<div/>').attr("id",progressbarID).appendTo($("#progressDiv"));
		        		$('#' + progressbarID).progressbar({
							value: 0 ,
							height : 22,
							width : "500px"
						}); 
		        		data.progressbarID = progressbarID;
		        		$('<br/>').appendTo($("#progressDiv"));
		        	}
		        },
				progress : function (e, data) {
					if(data.hasOwnProperty("progressbarID")) {
						var progress = parseInt(data.loaded / data.total * 100, 10);
						$('#' + data.progressbarID).progressbar('setValue', progress);
					}
				},
				progressall : function (e, data) {
					var progress = parseInt(data.loaded / data.total * 100, 10);
					$('#progressbar002').progressbar('setValue', progress);
				},
				fail : function (e, data) {
					$.messager.alert('提示','fail');
				}
			});
		});
		</script>
	</div>
	<hr/>

	<div>
		<h4>本地读取文件的MD5值：</h4>
		<input id="fileupload003" type="file" name="files[]" > <br/>
		MD5:(依赖函数 arrayBufferToWordArray(arrayBuffer)、swapendian32(val) ) <br/>
		<span id="md5003-1">MD5值</span>
		<div id="progressbar003-1" class="easyui-progressbar" data-options="text:'计算进度：{value}%'" style="width:500px;"></div><br/>
		
		MD5:(依赖文件 lib-typedarrays-min.js ) <br/>
		<span id="md5003-2">MD5值</span>
		<div id="progressbar003-2" class="easyui-progressbar" data-options="text:'计算进度：{value}%'"  style="width:500px;"></div><br/>
		<script type="text/javascript">
		$(document).ready(function () {
			if(canReadFile() == false){
				$.messager.alert('提示','此浏览器不支持读文件！');
				return ;
			}
			document.getElementById("fileupload003").addEventListener("change", function () {
				var file = document.getElementById("fileupload003").files[0];
				//创建md5Hash对象（基于CryptoJS）
				var md5Hash_1 = CryptoJS.algo.MD5.create();
				readFile(
						file, 
						function(chunks, currentChunk, e) {
							var data = arrayBufferToWordArray(e.target.result);
							md5Hash_1.update(data);
							var progress = parseInt(currentChunk * 100 / chunks, 10);
							$('#progressbar003-1').progressbar('setValue', progress);
							$("#md5003-1").text("计算中...");
						},
						function (md5) {
							var md5 = md5Hash_1.finalize().toString(CryptoJS.enc.Hex);
							$("#md5003-1").text(md5);
						}
					);
				
				//创建md5Hash对象（基于CryptoJS）
				var md5Hash_2 = CryptoJS.algo.MD5.create();
				readFile(
						file, 
						function(chunks, currentChunk, e) {
							var array = new Uint8Array(e.target.result);
							var data = CryptoJS.lib.WordArray.create(array);
							md5Hash_2.update(data);
							var progress = parseInt(currentChunk * 100 / chunks, 10);
							$('#progressbar003-2').progressbar('setValue', progress);
							$("#md5003-2").text("计算中...");
						},
						function (md5) {
							var md5 = md5Hash_2.finalize().toString(CryptoJS.enc.Hex);
							$("#md5003-2").text(md5);
						}
					);
			});
		});
		
		function readFile(file, work, callback) {
			// 文件读取对象 HTML5
			var fileReader = new FileReader();
			// 分割文件对象
			var blobSlice = File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice
			// 文件块大小 20KB
			var chunkSize = 20 * 1024;
			var chunks = Math.ceil(file.size / chunkSize);
			var currentChunk = 0;
			//每块文件读取完毕之后的处理
			fileReader.onload = function (e) {
				currentChunk++;
				var workResult = work(chunks, currentChunk, e);
				if (currentChunk < chunks) {
					// 继续读取文件
					loadNext();
				} else {
					// 文件读取完成
					callback(workResult);
				}
			};
			// 读取下一个文件块
			function loadNext() {
				var start = currentChunk * chunkSize;
				var end = start + chunkSize >= file.size ? file.size : start + chunkSize;
				var blob = file.slice(start, end);
				fileReader.readAsArrayBuffer(blob);
			}
			loadNext();
		}
	    function canReadFile() {
	        try {
	            // Check for FileApi
	            if (typeof FileReader == "undefined") {
	            	return false;
	            }
	            // Check for Blob and slice api
	            if (typeof Blob == "undefined") {
	            	return false;
	            }
	            var blob = new Blob();
	            if (!blob.slice && !blob.webkitSlice) {
	            	return false;
	            }
	            // Check for Drag-and-drop
	            if (!('draggable' in document.createElement('span'))) {
	            	return false;
	            }
	        } catch (e) {
	            return false;
	        }
	        return true;
	    }
		// 数据转换
		function arrayBufferToWordArray(arrayBuffer) {
			var fullWords = Math.floor(arrayBuffer.byteLength / 4);
			var bytesLeft = arrayBuffer.byteLength % 4;
			var u32 = new Uint32Array(arrayBuffer, 0, fullWords);
			var u8 = new Uint8Array(arrayBuffer);
			var cp = [];
			for (var i = 0; i < fullWords; ++i) {
				cp.push(swapendian32(u32[i]));
			}
			if (bytesLeft) {
				var pad = 0;
				for (var i = bytesLeft; i > 0; --i) {
					pad = pad << 8;
					pad += u8[u8.byteLength - i];
				}
				for (var i = 0; i < 4 - bytesLeft; ++i) {
					pad = pad << 8;
				}
				cp.push(pad);
			}
			return CryptoJS.lib.WordArray.create(cp, arrayBuffer.byteLength);
		};
		// 数据转换
		function swapendian32(val) {
			return (((val & 0xFF) << 24)
				 | ((val & 0xFF00) << 8)
				 | ((val >> 8) & 0xFF00)
				 | ((val >> 24) & 0xFF)) >>> 0;
		}
		</script>
	</div>
	<hr/>

	<div>
		<h4>上传文件时优先秒传，秒传失败再真正上传：</h4>
		<input id="fileupload004" type="file" name="files[]" style="margin-right: 20px"> 
		<input type="button" value="开始上传" onclick="start();" ><br/>
		秒传进度: <span id="uploadLazyToLocal004"></span><div id="progressbar004-1" class="easyui-progressbar" style="width:500px;"></div><br/>
		上传进度: <span id="uploadToLocal004"></span><div id="progressbar004-2" class="easyui-progressbar" style="width:500px;"></div><br/>
		
		<script type="text/javascript">
		
		function start() {
			$('#uploadLazyToLocal004').text("");
			$('#uploadToLocal004').text("");
			$('#progressbar004-1').progressbar('setValue', 0);
			$('#progressbar004-2').progressbar('setValue', 0);
			
			var files = $("#fileupload004").prop('files');
			var file = null;
			if(files.length > 0) {
				file = files[0];
			} else {
				$.messager.alert('提示','未选择文件！');
			}
			var md5Hash = CryptoJS.algo.MD5.create();
			readFile(
					file, 
					function(chunks, currentChunk, e) {
						var array = new Uint8Array(e.target.result);
						var data = CryptoJS.lib.WordArray.create(array);
						md5Hash.update(data);
						var progress = parseInt(currentChunk * 100 / chunks, 10);
						$('#progressbar004-1').progressbar('setValue', progress);
					},
					function (md5) {
						var md5 = md5Hash.finalize().toString(CryptoJS.enc.Hex);
						uploadLazyToLocal(file.name, md5, "MD5");
					}
				);
		}
		
		function uploadLazyToLocal(fileName, fileDigest, digestType) {
			$.post("${pageScope.mvcPath}/fileupload/uploadLazy", 
					{ fileName : fileName, fileDigest : fileDigest, digestType : digestType },
					function (data) {
						if(data.success == true){
							$('#uploadLazyToLocal004').text("秒传成功");
						} else {
							$('#uploadLazyToLocal004').text("秒传失败");
							uploadToLocal();
						}
				},"json");
		}
		
		function uploadToLocal() {
			$('#fileupload004').fileupload({
				url : "${pageScope.mvcPath}/fileupload/upload",
				type : "POST",
				dataType : "json",
				autoUpload : false,
				progress : function (e, data) {
					var progress = parseInt(data.loaded / data.total * 100, 10);
					$('#progressbar004-2').progressbar('setValue', progress);
				},
				done : function (e, data) {
					$('#uploadToLocal004').text("上传成功");
				},
				fail : function (e, data) {
					$.messager.alert('提示','上传失败');
				},
				always : function (e, data) {
					//设置 utoUpload : false 不需要
					$('#fileupload004').fileupload('destroy');
				}
		    });
			
			var jqXHR = $('#fileupload004').fileupload('send', {
				files : $("#fileupload004").prop('files')
			}).error(function (jqXHR, textStatus, errorThrown) {
				if (errorThrown === 'abort') {
					alert('已取消上传');
				}
			});
			
			/*
			
			
			$('button.cancel').click(function (e) {
				jqXHR.abort();
			});
			*/
		}
		</script>
	</div>
	<hr/>
	
</body>
</html>